package com.hubu.admin.utils;

//import io.swagger.annotations.ApiModelProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 统一API对象返回
 * @param <T>
 * @Author: TanXJ
 * @Date: 2021/10/13 9:31
 */
@Data
@Slf4j

@NoArgsConstructor
public class Result<T> {
    /** 状态码 */
    private Integer code;

    /** 返回消息 */
    private String message;

    /** 状态 */
    private boolean status;



    /** 返回数据 */
    private T data;

    public Result(Integer code, String message, boolean status, T data) {
        this.code = code;
        this.message = message;
        this.status = status;
        this.data = data;
    }

    public Result(ResultCode resultCode, boolean status, T data) {
        this.code = resultCode.getCode();
        this.message = resultCode.getMessage();
        this.status = status;
        this.data = data;
    }

    public Result(ResultCode resultCode, boolean status) {
        this.code = resultCode.getCode();
        this.message = resultCode.getMessage();
        this.status = status;
        this.data = null;
    }

    public static <T> Result success() {
        return new Result<>(ResultCode.OK, true);
    }

    public static <T> Result message(String message) {
        return new Result<>(ResultCode.OK.getCode(), message, true, null);
    }

    public static <T> Result success(T data) {
        return new Result<>(ResultCode.OK, true, data);
    }

    public static <T> Result fail() {
        return new Result<>(ResultCode.ERROR, false);
    }

    public static <T> Result fail(ResultCode resultCode) {
        return new Result<>(resultCode, false);
    }

    public static <T> Result fail(Integer code, String message) {
        return new Result<>(code, message, false, null);
    }

    public static <T> Result fail(ResultCode resultCode, T data) {
        return new Result<>(resultCode, false, data);
    }

    public static <T> Result fail(Integer code, String message, T data) {
        return new Result<>(code, message, false, data);
    }

    public static HttpServletResponse setReturnJson(HttpServletResponse response, String message) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        log.error(message);
        String s =new ObjectMapper().writeValueAsString(Result.fail(404, message));
        response.getWriter().write(s);
        return response;
    }
}
